<template>
    <el-dialog :model-value="dialogVisible" :title="type == 'add' ? '新增' : '编辑'" width="800px" :before-close="handleClose" append-to-body>
        <el-form ref="formRef" :model="dataForm" label-width="100px" :rules="rules" :inline="false">
            <el-form-item label="用户姓名" prop="depId">
                <el-select v-model="dataForm.depId" :loading="userLoading" class="w100p" placeholder="请输入用户名搜索"
                    :disabled="type == 'edit'" :remote-method="remoteMethod" clearable filterable remote reserve-keyword>
                    <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px;">[{{
                            item.email
                        }}]</span>
                    </el-option>
                </el-select>

            </el-form-item>
            <el-form-item label="成本中心" prop="costCenterIdList">
                <AllSelect style="width:100%" v-model="dataForm.costCenterIdList" @select="selectCostCenter"
                    :backValue="dataForm.costCenterIdList"></AllSelect>
            </el-form-item>
            <el-form-item label="状态" prop="state">
                <el-select v-model="dataForm.state" class="w100p" placeholder="请选择状态">
                    <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit()" :loading="loading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElLoading } from 'element-plus'
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    type: {
        default: 'add',
        type: String

    },
    editData: {
        type: Object,
        default: () => { }
    }

})


const userList = ref([])

const dataForm = ref({
    depId: '',
    costCenterIdList: [],
    state: ''
})
const statusList = ref([
    { label: '有效', value: '1' },
    { label: '暂停使用', value: '0' }
])

const loading = ref(false)

const userLoading = ref(false)

const rules = reactive({
    depId: [
        {
            required: true,
            message: '请选择用户',
            trigger: 'blur'
        },
    ],
    state: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'blur'
        },
    ],
    costCenterIdList: [
        {
            required: true,
            message: '请选择成本中心',
            trigger: 'blur'
        },
    ],
})

const formRef = ref(null)

const emit = defineEmits(['on-update', 'handleClose'])

const costCenterList = ref([])

const loadingFull = ref(null)

const timer = ref(null)

const getDetail = () => {
    const { departmentId, email, name, state, id, positionId, positionName } = props.editData
    const costList = props.editData.costCenterList
    const curUserObj = email + name 
    const userFind = userList.value.find((item) => {
        let itemObj = item.email + item.name 
        if (itemObj == curUserObj) return item
    })
    let data = { state, id, positionId, positionName }
    if (userFind) data.depId = userFind.id
    data.costCenterIdList = costList.map(item => item.centerCode)
    costCenterList.value = costList
    dataForm.value = data

}

// 获取成用户列表
const getList = (query = '') => {
    const params = {
        page: 1,
        rows: 100,
        params: {
            "name": query
        }
    }

    api.publicApi.passportUserList(params).then(res => {
        const { rows } = res
        userList.value = rows
         if (props.type == 'edit') getDetail()
    })

}

// 搜索发送请求
const remoteMethod = (query) => {
    if (query) {
        clearTimeout(timer.value)
        userLoading.value = true
        timer.value = setTimeout(() => {
            userLoading.value = false
            getList(query)
        }, 500)
    } else {
        options.value = []
    }
}


onMounted(() => {
    if (props.type == 'edit') getList(props.editData.name)

});
const selectCostCenter = (e) => {
    console.log(e, 'eeeeeee')
    costCenterList.value = e
}

// 关闭
const handleClose = () => {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    emit('handleClose')

}

const submit = () => {
    const { depId, positionId, positionName, state, id } = dataForm.value
    if (!formRef) return
    formRef.value.validate(valid => {

        if (valid) {
            const { departmentId, email, department, name, rankCode, rankName } = userList.value.find(item => item.id == depId)
            console.log(departmentId, 'departmentId')
            const costList = costCenterList.value.map(item => {
                return {
                    centerCode: item.centerCode,
                    centerName: item.centerName
                }
            })
            let data = {
                departmentId,
                department,
                email,
                name,
                positionId: rankCode || positionId,
                positionName: rankName || positionName,
                state,
                costCenterList: costList
            }

            const interFaceObj = {
                'edit': 'permissionsUpdate',
                'add': 'permissionsAdd'
            }
            if (props.type == 'edit') data.id = id
            console.log(valid, 'validvalidvalid', costCenterList.value)
            api.budgetConfig[interFaceObj[props.type]](data).then(res => {
                emit('on-update')
                handleClose()
                ElMessage.success('操作成功')
            })

        } else {
            console.log('error submit!')
            return false
        }
    })
}


</script>



<style lang="scss" scoped>
.w100p {
    width: 100%;
}

.prompt {
    margin: 0 20px;
    font-size: 14px;
}
</style>